package desu.bean;

import desu.db.Anime_full;
import desu.nya.DAO.AnimeFactory;
import desu.nya.*;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;


@ManagedBean
@RequestScoped
public class MainBean{
    private String hell="Hello world";
    private List<Genre> genreList;
//    private List<String> nickList;
    private List<Anime> animeList;
    private List<Studio> studioList;
    private List<StreamedContent> coverStreamList;
    
    private Otaku currentOtaku=null;
    private Anime selectedAnime;
    private Anime defaultAnime;
    private UploadedFile file;
    private FileUpload fu;

    private AnimeFactory factory=null;
    private StreamedContent animeImg;
    private StreamedContent notFoundImg;
    private StreamedContent notFoundSmallImg;
    private boolean rendList;

    public void setDefaultAnime(Anime defaultAnime) {
        this.defaultAnime = defaultAnime;
    }

    
    public boolean isRendList() {
        return rendList;
    }

    public List<StreamedContent> getCoverStreamList() {
        return coverStreamList;
    }

    public void setCoverStreamList(List<StreamedContent> coverStreamList) {
        this.coverStreamList = coverStreamList;
    }

    
    
    public FileUpload getFu() {
        return fu;
    }

    public void setFu(FileUpload fu) {
        this.fu = fu;
    }

    
    public Anime getSelectedAnime() {
        return selectedAnime;
    }

    public void setSelectedAnime(Anime selectedAnime) {
        this.selectedAnime = selectedAnime;
    }
        
    public List<Studio> getStudioList() {
        return studioList;
    }

    public List<Genre> getGenreList() throws SQLException {
        return genreList;
    }

    public void setGenreList(List<Genre> genreList) {
        this.genreList = genreList;
    }

    public void setStudioList(List<Studio> studioList) {
        this.studioList = studioList;
    }

    
    public String getHell() {
        return hell;
    }

    public void setHell(String hell) {
        this.hell = hell;
    }

    public void setAnimeList(List<Anime> animeList) {
        this.animeList = animeList;
    }

    public List<Anime> getAnimeList() {
        return animeList;
    }

    public StreamedContent getAnimeImg() {
        return animeImg;
    }

    public void setAnimeImg(StreamedContent animeImg) {
        this.animeImg = animeImg;
    }
    
    
    
    
    @PostConstruct
    public void replenish(){
        int startYear=1980;
        defaultAnime=new Anime("not found", null, null, 0, 0, "not found", null, null, hell);
        defaultAnime.setId(0l);
        String filePath="d:\\Fess\\work\\AnimeDB\\AnimeList\\web\\src\\not_found.jpg";
        String fileSmallPath="d:\\Fess\\work\\AnimeDB\\AnimeList\\web\\src\\not_found_small.jpg";
        FileInputStream file=null;
        byte[] b=null;
        try {
            file = new FileInputStream(filePath);
            if(file==null){
                System.err.println("File Read Error");
                return;
            }
            int count=file.available();
            b=new byte[count];
            file.read(b);
            notFoundImg=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
            file = new FileInputStream(fileSmallPath);
            if(file==null){
                System.err.println("File Read Error");
                return;
            }
            count=file.available();
            b=new byte[count];
            file.read(b);
            notFoundSmallImg=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
        }
        catch(Exception ex){
            FacesContext context=FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"File not found","Image not_found.jpg not found"));
        }
        try {
            factory=AnimeFactory.getInstance();
            animeList=factory.getAnimeDAO().getAllAnime();
            if(animeList!=null&&!animeList.isEmpty())
                selectedAnime=animeList.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
   
    public void uploadTheFile(){
        System.err.println("-----------------+++--------------------");
        FileUploadEvent event=null;
        FacesMessage msg = new FacesMessage("Succesful", " is uploaded.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
        if(event==null)return;
        file=event.getFile();
        System.err.println("-----------------+++--------------------");
        byte[] buffer = null;
        try {
            file.getInputstream().read(buffer);
        } catch (IOException ex) {
        }
        selectedAnime.setCover(new Cover(buffer));
    }
    
    public StreamedContent getImage() {
        Long id=0L;
        String s=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("coverId");
        String imgMode=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("imgMode");
        int mode=1;
        if(imgMode!=null&&imgMode.equals("small"))
            mode=2;
        System.out.println("coverId="+s+" ?????????????");
        
        if(s==null){
            System.err.println("-----------Get Image error #1----------");
            return notFoundImg;
        }
        try {
            id=Long.parseLong(s);
            StreamedContent sc=factory.getCoverDAO().getCoverImage(id, mode);
            if(sc==null)
                return mode==1?notFoundImg:notFoundSmallImg;
            return sc;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("Get Image error #2");
        }
        return mode==1?notFoundImg:notFoundSmallImg;
    }
    
    public StreamedContent getSmallImage(Long id) {
//        Long id=0L;
        String s=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("coverId");
        System.out.println("coverId="+s+" ?????????????");
        if(s==null){
            System.err.println("-----------Get SmallImage error #1----------");
            return  notFoundSmallImg;
        }
        id=Long.parseLong(s);
        try {
//            byte[] b=null;
//            b=factory.getCoverDAO().getCoverByID(id).getSmallImage();
//            if(b==null)
//                return coverStreamList.get(0);
//            StreamedContent tempStream=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
//            return tempStream;
            return factory.getCoverDAO().getCoverImage(id, 2);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("Get SmallImage error #2");
        }
        return notFoundSmallImg;
    }
    
    public List<String> getGenreListById(Anime anime){
        if(anime==null)anime=selectedAnime;
        if(anime==null)return null;
//        List<Genre> list=new ArrayList<Genre>();
        List<String> list=null;
        try {
            list=factory.getGenreListDAO().getAllGenreByAnime(anime.getId());
            System.out.println("ID get: "+anime.getId()+"Genre by Anime founded: "+list.size());
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext context=FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Genre not found","Genre founding error"));
            System.err.println("Genre founding error");
            list.add(null);
        }
        return list;
    }
    
    public double getRateOfAnime(){
        double ret=-1;
        Long id=0L;
        String s=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("rate_id");
        if(s==null){
            System.err.println("-----------Get Rate error #1----------");
            return  0;
        }
        id=Long.parseLong(s);
        try {
            Anime anime=factory.getAnimeDAO().getAnimeByID(id);
            Rating rate=factory.getRatingDAO().getRateByNickAndAnime(currentOtaku, anime);
            ret=rate.getRate();
            
        } catch (SQLException ex) {
            System.err.println("-----------Get Rate error #2----------");
            FacesContext context=FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"SQL exception","Rating not found"));
        }
        return ret;
    }
    
    public void detailDisplay(String id){
        Long lId=Long.valueOf(id);
        rendList=true;
//        for(Anime anime:animeList){
//            if(anime.getId().equals(lId))
//                selectedAnime=anime;
//        }
        System.out.println("Detail of anime: "+id);
    }
    
    public void allDisplay(){
        rendList=false;
        System.out.println("All anime Display: ");
    }
    
    public void animeSelect(){
        String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("animeId");
        Long lId=Long.valueOf(id);
        try {
            selectedAnime=factory.getAnimeDAO().getAnimeByID(lId);
            rendList=true;
        } catch (SQLException ex) {
            FacesContext context=FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Anime Select error",ex.getMessage()));
        }
        
    }
 
    public void ongoingShow(){
        try {
            animeList=(List<Anime>)factory.getAnimeDAO().getOngoings();
        } catch (SQLException ex) {
            ex.printStackTrace();
            FacesContext context=FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"SQL exception","Ongoing not found"));
        }
    }
    
    public String getAnimeAddPath(){
        return "animeAdd";
    }
    
    public void saveAllAnimeInFile(){
        try {
            Anime_full aFull=new Anime_full();
            factory=AnimeFactory.getInstance();
            aFull.setAnime(factory.getAnimeDAO().getAllAnime());
            aFull.setCover(factory.getCoverDAO().getAllCover());
            aFull.setGenre(factory.getGenreDAO().getAllGenre());
            aFull.setRating(factory.getRatingDAO().getAllRating());
            aFull.setStudio(factory.getStudioDAO().getAllStudio());
            aFull.setTypeEd(factory.getTypeEdDAO().getAllTypeEd());
            FileOutputStream fos=new FileOutputStream("C:\\out.txt");
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            oos.writeObject(aFull);
            oos.flush();
            oos.close();
        } catch (SQLException ex) {
            Logger.getLogger(MainBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex){
            ex.printStackTrace();
        } catch (IOException ex){
            ex.printStackTrace();
        }
    }
    
    public void restoreFromFile(){
        ObjectInputStream ois = null;
        try {
            FileInputStream fis=new FileInputStream("C:\\out.txt");
            ois = new ObjectInputStream(fis);
            Anime_full aFull=(Anime_full)ois.readObject();
            ois.close();
            System.err.println(aFull.getAnime().get(aFull.getAnime().size()-1).getName());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch(ClassNotFoundException ex){
            
        }
        finally {
                
        }
    }
}
